#include "queen.h"

int solutions_count = 0;

board::board ()
{
    fill_n ((char*) chess_board, SIZE*SIZE, 'x');
}

board::board (board& Cersei)
{
    copy ((char*) Cersei.chess_board, 
          (char*) Cersei.chess_board + SIZE * SIZE,
          (char*) chess_board);
}

void board::print ()
{
    int i, j;
    cout << endl << setw(3) << "";
    for (i = 0; i < SIZE; ++i)
        cout << setw (2) << i;
    cout << endl;
    for (i = 0; i < SIZE; ++i)
    {
        cout << setw (3) << i;
        for (j = 0; j < SIZE; ++j)
            cout << setw (2) << chess_board[i][j];
        cout << endl;
    }
    cout << endl;
}

char* board::operator [] (int index)
{
    return chess_board[index];
}

queens::queens ()
{
    cols = vector<int> (SIZE, 0);
}

void queens::fights (int start_row){
    int j;
    for (j = 0; j < SIZE; ++j)
        if (is_conflict(start_row, j))
        {
            board tmp = chess_board;
            chess_board[start_row][j] = 'Q';
            cols[start_row] = j;
            if (start_row == SIZE - 1)
            {
                chess_board.print ();
                ++solutions_count;
                break;
            }
            queens Cersei (*this);
            Cersei.fights (start_row + 1);
            chess_board = tmp;
    }
}

bool queens::is_conflict (int row, int col )
{
    int i;
    bool is_valid = true;
    for (i = 0; i < row; ++i)
    {
        if (cols[i] == col ||
            col - cols[i] == row - i ||
            col - cols[i] == i - row)
        {
            is_valid = false;
            break;
        }
    }

    return is_valid;
}
